'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { formatDate } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { Plus, Eye, Edit2, Trash2, MessageSquare, Users, Calendar, Search, Star, Bell } from 'lucide-react';

interface Announcement {
  id: string;
  title: string;
  content: string;
  type: string;
  priority: string;
  is_active: boolean;
  is_banner: boolean;
  is_popup: boolean;
  is_pinned: boolean;
  start_date?: string;
  end_date?: string;
  target_audience: string;
  created_by: string;
  created_at: string;
  updated_at: string;
  view_count: number;
  read_count: number;
}

interface AnnouncementStats {
  total_announcements: number;
  active_announcements: number;
  total_reads: number;
  avg_read_rate: number;
}

interface CreateAnnouncementForm {
  title: string;
  content: string;
  announcement_type: string;
  priority: string;
  target_audience: string;
  is_pinned: boolean;
  is_banner: boolean;
  is_popup: boolean;
  start_date?: string;
  end_date?: string;
}

export default function AnnouncementsPage() {
  const { currentChain } = useChain();
  const queryClient = useQueryClient();
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingAnnouncement, setEditingAnnouncement] = useState<Announcement | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [selectedAnnouncement, setSelectedAnnouncement] = useState<Announcement | null>(null);

  // Form state for announcement creation/editing
  const [formData, setFormData] = useState<CreateAnnouncementForm>({
    title: '',
    content: '',
    announcement_type: 'general',
    priority: 'medium',
    target_audience: 'all',
    is_pinned: false,
    is_banner: false,
    is_popup: false,
    start_date: '',
    end_date: ''
  });

  // Fetch announcement statistics
  const { data: stats, isLoading: statsLoading, error: statsError } = useQuery<AnnouncementStats>({
    queryKey: ['announcement-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/admin/announcements/stats');
      return response.data;
    },
  });

  // Fetch all announcements
  const { data: announcements, isLoading: announcementsLoading, error: announcementsError } = useQuery<Announcement[]>({
    queryKey: ['announcements', currentChain, searchTerm, typeFilter, statusFilter],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const params = new URLSearchParams();
      if (searchTerm) params.append('search', searchTerm);
      if (typeFilter !== 'all') params.append('announcement_type', typeFilter);
      if (statusFilter !== 'all') params.append('status', statusFilter);
      
      const response = await client.get(`/api/v1/admin/announcements/all?${params.toString()}`);
      return response.data;
    },
  });

  // Create announcement mutation
  const createAnnouncementMutation = useMutation({
    mutationFn: async (announcementData: CreateAnnouncementForm) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post('/api/v1/admin/announcements/create', announcementData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['announcements'] });
      queryClient.invalidateQueries({ queryKey: ['announcement-stats'] });
      setShowCreateForm(false);
      resetForm();
    },
  });

  // Update announcement mutation
  const updateAnnouncementMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: Partial<CreateAnnouncementForm> }) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.put(`/api/v1/admin/announcements/${id}`, data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['announcements'] });
      queryClient.invalidateQueries({ queryKey: ['announcement-stats'] });
      setEditingAnnouncement(null);
      resetForm();
    },
  });

  // Delete announcement mutation
  const deleteAnnouncementMutation = useMutation({
    mutationFn: async (id: string) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.delete(`/api/v1/admin/announcements/${id}`);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['announcements'] });
      queryClient.invalidateQueries({ queryKey: ['announcement-stats'] });
    },
  });

  const resetForm = () => {
    setFormData({
      title: '',
      content: '',
      announcement_type: 'general',
      priority: 'medium',
      target_audience: 'all',
      is_pinned: false,
      is_banner: false,
      is_popup: false,
      start_date: '',
      end_date: ''
    });
  };

  const handleCreateAnnouncement = () => {
    setShowCreateForm(true);
    resetForm();
  };

  const handleEditAnnouncement = (announcement: Announcement) => {
    setEditingAnnouncement(announcement);
    setFormData({
      title: announcement.title,
      content: announcement.content,
      announcement_type: announcement.type,
      priority: announcement.priority,
      target_audience: announcement.target_audience,
      is_pinned: announcement.is_pinned,
      is_banner: announcement.is_banner,
      is_popup: announcement.is_popup,
      start_date: announcement.start_date?.split('T')[0] || '',
      end_date: announcement.end_date?.split('T')[0] || ''
    });
    setShowCreateForm(true);
  };

  const handleDeleteAnnouncement = async (id: string) => {
    if (window.confirm('Are you sure you want to delete this announcement?')) {
      deleteAnnouncementMutation.mutate(id);
    }
  };

  const handleSubmitAnnouncement = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const submitData = {
      ...formData,
      start_date: formData.start_date ? `${formData.start_date}T00:00:00Z` : undefined,
      end_date: formData.end_date ? `${formData.end_date}T23:59:59Z` : undefined,
    };

    if (editingAnnouncement) {
      updateAnnouncementMutation.mutate({ id: editingAnnouncement.id, data: submitData });
    } else {
      createAnnouncementMutation.mutate(submitData);
    }
  };

  const getBadgeColor = (type: string, field: 'type' | 'priority' = 'type') => {
    if (field === 'type') {
      const colors: Record<string, string> = {
        system: 'bg-blue-100 text-blue-800',
        mining: 'bg-green-100 text-green-800',
        reward: 'bg-yellow-100 text-yellow-800',
        security: 'bg-red-100 text-red-800',
        promotion: 'bg-purple-100 text-purple-800',
        general: 'bg-gray-100 text-gray-800',
      };
      return colors[type] || colors.general;
    } else {
      const colors: Record<string, string> = {
        low: 'bg-gray-100 text-gray-800',
        medium: 'bg-yellow-100 text-yellow-800',
        high: 'bg-orange-100 text-orange-800',
        critical: 'bg-red-100 text-red-800',
      };
      return colors[type] || colors.medium;
    }
  };

  const formatNumber = (num: number) => {
    return new Intl.NumberFormat().format(num);
  };

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Announcement Management</h1>
              <p className="text-gray-500">Manage system-wide announcements and notifications</p>
            </div>
            <Button onClick={handleCreateAnnouncement} className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              Create Announcement
            </Button>
          </div>

          {/* Statistics Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Announcements</CardTitle>
                <MessageSquare className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats?.total_announcements || 0}</div>
                <p className="text-xs text-muted-foreground">All announcements created</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Active Announcements</CardTitle>
                <Bell className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{stats?.active_announcements || 0}</div>
                <p className="text-xs text-muted-foreground">Currently published</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Total Reads</CardTitle>
                <Eye className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{formatNumber(stats?.total_reads || 0)}</div>
                <p className="text-xs text-muted-foreground">Total user reads</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">Avg Read Rate</CardTitle>
                <Users className="h-4 w-4 text-muted-foreground" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{(stats?.avg_read_rate || 0).toFixed(1)}%</div>
                <p className="text-xs text-muted-foreground">Average engagement</p>
              </CardContent>
            </Card>
          </div>

          {/* Filters */}
          <Card>
            <CardHeader>
              <CardTitle>Filter Announcements</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Search</label>
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <input
                      type="text"
                      className="pl-10 w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                      placeholder="Search announcements..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
                  <select
                    className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                    value={typeFilter}
                    onChange={(e) => setTypeFilter(e.target.value)}
                  >
                    <option value="all">All Types</option>
                    <option value="system">System</option>
                    <option value="mining">Mining</option>
                    <option value="reward">Reward</option>
                    <option value="security">Security</option>
                    <option value="promotion">Promotion</option>
                    <option value="general">General</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
                  <select
                    className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                  >
                    <option value="all">All Status</option>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                    <option value="draft">Draft</option>
                  </select>
                </div>
                <div className="flex items-end">
                  <Button
                    onClick={() => {
                      setSearchTerm('');
                      setTypeFilter('all');
                      setStatusFilter('all');
                    }}
                    variant="outline"
                    className="w-full"
                  >
                    Clear Filters
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Announcements List */}
          <Card>
            <CardHeader>
              <CardTitle>Announcements</CardTitle>
              <CardDescription>Manage your system announcements</CardDescription>
            </CardHeader>
            <CardContent>
              {announcementsLoading ? (
                <div className="flex items-center justify-center h-32">
                  <div className="text-sm text-gray-500">Loading announcements...</div>
                </div>
              ) : announcements && announcements.length > 0 ? (
                <div className="space-y-4">
                  {announcements.map((announcement) => (
                    <div key={announcement.id} className="border rounded-lg p-4 hover:bg-gray-50 transition-colors">
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-3 mb-2">
                            <h3 className="font-medium text-gray-900 truncate">{announcement.title}</h3>
                            <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getBadgeColor(announcement.type, 'type')}`}>
                              {announcement.type}
                            </span>
                            <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getBadgeColor(announcement.priority, 'priority')}`}>
                              {announcement.priority}
                            </span>
                            {announcement.is_pinned && (
                              <Star className="h-4 w-4 text-yellow-500" />
                            )}
                            {announcement.is_active ? (
                              <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-800">
                                Active
                              </span>
                            ) : (
                              <span className="inline-flex px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800">
                                Inactive
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-600 mb-2 line-clamp-2">{announcement.content}</p>
                          <div className="flex items-center gap-4 text-xs text-gray-500">
                            <span className="flex items-center gap-1">
                              <Eye className="h-3 w-3" />
                              {formatNumber(announcement.view_count)} views
                            </span>
                            <span className="flex items-center gap-1">
                              <Users className="h-3 w-3" />
                              {formatNumber(announcement.read_count)} reads
                            </span>
                            <span className="flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              {formatDate(announcement.updated_at)}
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center gap-2 ml-4">
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => setSelectedAnnouncement(announcement)}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleEditAnnouncement(announcement)}
                          >
                            <Edit2 className="h-4 w-4" />
                          </Button>
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleDeleteAnnouncement(announcement.id)}
                            className="text-red-600 hover:text-red-700"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <MessageSquare className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-sm font-medium text-gray-900">No announcements</h3>
                  <p className="mt-1 text-sm text-gray-500">Get started by creating your first announcement.</p>
                  <div className="mt-6">
                    <Button onClick={handleCreateAnnouncement}>
                      <Plus className="h-4 w-4 mr-2" />
                      Create Announcement
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Create/Edit Announcement Modal */}
          {showCreateForm && (
            <div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center p-4 z-50">
              <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div className="px-6 py-4 border-b border-gray-200">
                  <h3 className="text-lg font-medium text-gray-900">
                    {editingAnnouncement ? 'Edit Announcement' : 'Create Announcement'}
                  </h3>
                </div>
                <form onSubmit={handleSubmitAnnouncement} className="px-6 py-4 space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Title</label>
                    <input
                      type="text"
                      required
                      className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                      value={formData.title}
                      onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Content</label>
                    <textarea
                      required
                      rows={4}
                      className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                      value={formData.content}
                      onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                    />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Type</label>
                      <select
                        className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        value={formData.announcement_type}
                        onChange={(e) => setFormData({ ...formData, announcement_type: e.target.value })}
                      >
                        <option value="system">System</option>
                        <option value="mining">Mining</option>
                        <option value="reward">Reward</option>
                        <option value="security">Security</option>
                        <option value="promotion">Promotion</option>
                        <option value="general">General</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Priority</label>
                      <select
                        className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        value={formData.priority}
                        onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                      >
                        <option value="low">Low</option>
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                        <option value="critical">Critical</option>
                      </select>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
                      <input
                        type="date"
                        className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        value={formData.start_date}
                        onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">End Date</label>
                      <input
                        type="date"
                        className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        value={formData.end_date}
                        onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
                      />
                    </div>
                  </div>
                  <div className="space-y-3">
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="is_pinned"
                        className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                        checked={formData.is_pinned}
                        onChange={(e) => setFormData({ ...formData, is_pinned: e.target.checked })}
                      />
                      <label htmlFor="is_pinned" className="ml-2 block text-sm text-gray-900">Pin to top</label>
                    </div>
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="is_banner"
                        className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                        checked={formData.is_banner}
                        onChange={(e) => setFormData({ ...formData, is_banner: e.target.checked })}
                      />
                      <label htmlFor="is_banner" className="ml-2 block text-sm text-gray-900">Show as banner</label>
                    </div>
                    <div className="flex items-center">
                      <input
                        type="checkbox"
                        id="is_popup"
                        className="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
                        checked={formData.is_popup}
                        onChange={(e) => setFormData({ ...formData, is_popup: e.target.checked })}
                      />
                      <label htmlFor="is_popup" className="ml-2 block text-sm text-gray-900">Show as popup</label>
                    </div>
                  </div>
                </form>
                <div className="px-6 py-4 border-t border-gray-200 flex justify-end gap-3">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => {
                      setShowCreateForm(false);
                      setEditingAnnouncement(null);
                      resetForm();
                    }}
                  >
                    Cancel
                  </Button>
                  <Button
                    onClick={handleSubmitAnnouncement}
                    disabled={createAnnouncementMutation.isPending || updateAnnouncementMutation.isPending}
                  >
                    {editingAnnouncement ? 'Update' : 'Create'} Announcement
                  </Button>
                </div>
              </div>
            </div>
          )}

          {/* View Announcement Modal */}
          {selectedAnnouncement && (
            <div className="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center p-4 z-50">
              <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div className="px-6 py-4 border-b border-gray-200">
                  <h3 className="text-lg font-medium text-gray-900">{selectedAnnouncement.title}</h3>
                  <div className="flex items-center gap-2 mt-2">
                    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getBadgeColor(selectedAnnouncement.type, 'type')}`}>
                      {selectedAnnouncement.type}
                    </span>
                    <span className={`inline-flex px-2 py-1 text-xs font-medium rounded-full ${getBadgeColor(selectedAnnouncement.priority, 'priority')}`}>
                      {selectedAnnouncement.priority}
                    </span>
                    {selectedAnnouncement.is_pinned && <Star className="h-4 w-4 text-yellow-500" />}
                  </div>
                </div>
                <div className="px-6 py-4">
                  <div className="prose max-w-none">
                    <p className="text-gray-900 whitespace-pre-wrap">{selectedAnnouncement.content}</p>
                  </div>
                  <div className="mt-6 pt-4 border-t border-gray-200">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="font-medium text-gray-700">Target Audience:</span>
                        <span className="ml-1 text-gray-900">{selectedAnnouncement.target_audience}</span>
                      </div>
                      <div>
                        <span className="font-medium text-gray-700">Created:</span>
                        <span className="ml-1 text-gray-900">{formatDate(selectedAnnouncement.created_at)}</span>
                      </div>
                      <div>
                        <span className="font-medium text-gray-700">Views:</span>
                        <span className="ml-1 text-gray-900">{formatNumber(selectedAnnouncement.view_count)}</span>
                      </div>
                      <div>
                        <span className="font-medium text-gray-700">Reads:</span>
                        <span className="ml-1 text-gray-900">{formatNumber(selectedAnnouncement.read_count)}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="px-6 py-4 border-t border-gray-200 flex justify-end">
                  <Button
                    onClick={() => setSelectedAnnouncement(null)}
                    variant="outline"
                  >
                    Close
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}